package net.freebytes.chat2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.Scanner;
import net.freebytes.chat.MessageTypeEnum;

public class UserClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().writeAndFlush(MessageTypeEnum.USER_REGISTER.getType() + "&我是用户:" + ctx.channel().id().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String[] messages = ((String) msg).split("&");
        String messageType = messages[0];
        if (MessageTypeEnum.USER_QUESTION.getType().equals(messageType)) {
            // 如果是智能客服
            System.out.println(messages[1]);
            System.out.println();

            Scanner scanner = new Scanner(System.in);
            String key = scanner.nextLine();

            ctx.channel().writeAndFlush(MessageTypeEnum.USER_QUESTION.getType() + "&" + key);
        } else if (MessageTypeEnum.RG_USER_MESSAGE.getType().equals(messageType)) {
            // 人工坐席
            String[] values = messages[1].split("\\|");
            String content = values[1];
            System.out.println("人工坐席说：" + content);
            System.out.println();

            Scanner scanner = new Scanner(System.in);
            String userContent = scanner.nextLine();

            // 人工坐席 Channel
            String toChannelId = values[0];
            userContent = MessageTypeEnum.RG_USER_MESSAGE.getType() + "&" + toChannelId + "|" + userContent;

            ctx.channel().writeAndFlush(userContent);
        }
    }
}
